package com.zyuuo.warehouse.ex.handler;


import com.zyuuo.warehouse.ex.ServiceException;
import com.zyuuo.warehouse.web.Result;
import com.zyuuo.warehouse.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result handleServiceException(ServiceException e){
        log.warn("程序运行过程中出现ServiceException，将统一处理！");
        log.warn("异常信息：{}", e.getMessage());
        return Result.fail(e);
    }

    @ExceptionHandler
    public Result handleBindException(BindException e) {
        log.warn("程序运行过程中出现BindException，将统一处理！");
        log.warn("异常信息：{}", e.getMessage());
        return Result.fail(ServiceCode.ERR_BAD_REQUEST, e.getFieldError().getDefaultMessage());
    }



    @ExceptionHandler
    public Result handleConstraintViolationExceptionExecutableException(ConstraintViolationException e) {
        log.warn("程序运行过程中出现BindException，将统一处理！");
        log.warn("异常信息：{}", e.getMessage());
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        String message="";
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            message+=constraintViolation.getMessage();
        }
        return Result.fail(ServiceCode.ERR_BAD_REQUEST, message);
    }

    @ExceptionHandler
    public Result handleThrowableException(Throwable e) {
        log.warn("程序运行过程中出现BindException，将统一处理！");
        log.warn("异常信息：{}", e.getMessage());
        String message = "【开发阶段专用】你的服务器端出了异常，请检查服务器端控制台中的异常信息，并补充处理此类异常的方法！";
        // String message = "服务器忙，请稍后再尝试！"; // 项目上线时应该使用此提示文本
        e.printStackTrace(); // 打印异常的跟踪信息，主要是为了在开发阶段更好的检查出现异常的原因
        return Result.fail(ServiceCode.ERR_UNKNOWN, message);
    }
}
